<template>
  <view>
    <!-- 顶部导航 -->
    <view
      class="topTabBar"
      :style="{ position: headerPosition, top: headerTop }"
    >
      <view
        class="grid"
        v-for="(grid, tbIndex) in orderType"
        :key="tbIndex"
        @tap="showType(tbIndex)"
      >
        <view class="text" :class="[tbIndex == tabbarIndex ? 'on' : '']">{{
          grid
        }}</view>
      </view>
    </view>
    <!-- 考虑非APP端长列表和复杂的DOM使用scroll-view会卡顿，所以漂浮顶部选项卡使用page本身的滑动 -->
    <view class="order-list">
      <!-- 下拉刷新 -->
      <view class="refresh-tip" v-if="isRefreshing">
        <text>正在刷新...</text>
      </view>
      <view class="list">
        <view class="onorder" v-if="list.length == 0">
          <image src="../../../static/img/noorder.png"></image>
          <view class="text"> 没有相关订单 </view>
        </view>
        <view class="row" v-for="(row, index) in list" :key="index">
          <view class="order-header">
            <view class="type">{{ getStatusText(row.status) }}</view>
            <view class="order-time">{{ formatOrderTime(row.orderTime) }}</view>
          </view>
          <view
            class="order-info"
            @tap="goOrderDetail(row)"
            v-for="(item, idx) in row.orderItems"
            :key="idx"
          >
            <view class="left">
              <image :src="getProductImage(item)"></image>
            </view>
            <view class="right">
              <view class="name">{{ getProductName(item) }}</view>
              <view class="price-number">
                ￥{{ item.pPrice || "0.00" }} x
                {{ item.pNumber || "0" }}
              </view>
            </view>
          </view>
          <view class="detail">
            <view class="number"
              >共{{ getTotalItems(row.orderItems) }}件商品</view
            >
            <view class="sum"
              >{{ getOrderPriceLabel(row.status) }}￥<view class="price">{{
                getDisplayOrderPrice(row)
              }}</view>
            </view>
            <view class="nominal">(含运费 ￥0.00)</view>
          </view>
          <view class="btns">
            <!-- 等待商家发货 -->
            <!-- <block v-if="row.status == 'PENDING_SHIP'">
              <view class="default" @tap="cancelOrder(row)">取消订单</view>
            </block> -->
            <!-- 商家已发货 -->
            <block v-if="row.status == 'SHIPPED'">
              <view class="pay" @tap="confirmReceive(row)">确认收货</view>
              <view class="pay" @tap="returnGoods(row)">我要退货</view>
            </block>
            <!-- 待付款状态 -->
            <block v-if="row.status == 'PENDING_PAYMENT'">
              <view class="default" @tap="viewRefundProgress(row)"
                >查看订单进度</view
              >
            </block>
            <!-- 交易已完成 -->
            <block v-if="row.status == 'COMPLETED'">
              <view class="default" @tap="addInvoiceInfo(row)"
                >添加发票抬头</view
              >
              <view class="default" @tap="viewInvoice(row)">查看发票</view>
              <view class="default" @tap="buyAgain(row)">再次购买</view>
            </block>
            <!-- 退货被拒绝，允许确认收货 -->
            <block v-if="row.status == 'RETURN_REJECTED'">
              <view class="pay" @tap="confirmReceive(row)">确认收货</view>
              <view class="default" @tap="viewRefundProgress(row)"
                >查看退货进度</view
              >
            </block>
            <!-- 其他退货相关状态 -->
            <block
              v-if="
                row.status == 'RETURN_REQUESTED' ||
                row.status == 'RETURN_APPROVED' ||
                row.status == 'REFUNDING'
              "
            >
              <view class="default" @tap="viewRefundProgress(row)"
                >查看退货进度</view
              >
            </block>

            <!-- 待确认 -->
            <block v-if="row.status == 'PENDING'">
              <view class="default" @tap="conformOrderFun(row, 'CONFIRMED')"
                >确认报价</view
              >
              <view class="default" @tap="conformOrderFun(row, 'CANCELLED')"
                >拒绝报价</view
              >
            </block>
            <!-- 已退货 -->
            <block v-if="row.status == 'RETURNED'">
              <view class="default" @tap="addInvoiceInfo(row)"
                >添加发票抬头</view
              >
              <view class="default" @tap="viewInvoice(row)">查看发票</view>
            </block>
            <!-- 订单已取消 -->
            <block v-if="row.status == 'CANCELLED'">
              <view class="default">已取消</view>
            </block>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import {
  getOrderList,
  cancelOrder,
  confirmReceive,
  applyRefund,
  saveInvoiceInfo,
  getInvoiceInfo,
} from "../../../common/api/orderList.js";
import { getFirstImage } from "@/common/utils/index.js";
import { conformOrder } from "@/common/api/product.js";

export default {
  // 页面配置
  onPullDownRefresh: true,
  data() {
    return {
      headerPosition: "fixed",
      headerTop: "0px",
      statusText: {
        // 后端实际状态枚举
        PENDING_SHIP: "待发货",
        SHIPPED: "待收货",
        PENDING_PAYMENT: "待付款",
        COMPLETED: "已完成",
        RETURN_REQUESTED: "退货申请中",
        RETURN_APPROVED: "退货已同意",
        RETURN_REJECTED: "退货被拒绝",
        RETURNED: "已退货",
        CANCELLED: "已取消",
        // 兼容旧键（如果还有使用）

        REFUNDING: "商品退货处理中",
        PENDING: "待确认",
      },
      orderType: [
        "全部",
        "待发货",
        "待收货",
        "待付款",
        // "申请退货",
        // "退货同意",
        // "退货拒绝",
        "退换货",
      ],
      orderList: [],
      list: [],
      tabbarIndex: 0,
      isRefreshing: false,
      isCancelling: false,
      addressId: "",
    };
  },
  onLoad(option) {
    //option为object类型，会序列化上个页面传递的参数
    let incomingIndex = Number(option.tbIndex);
    if (Number.isNaN(incomingIndex)) incomingIndex = 0;
    this.tabbarIndex = Math.min(4, Math.max(0, incomingIndex));

    // 根据tab索引加载对应状态的订单
    this.showType(this.tabbarIndex);
    //兼容H5下排序栏位置
    // #ifdef H5
    let Timer = setInterval(() => {
      let uniHead = document.getElementsByTagName("uni-page-head");
      if (uniHead.length > 0) {
        this.headerTop = uniHead[0].offsetHeight + "px";
        clearInterval(Timer); //清除定时器
      }
    }, 1);
    // #endif
  },
  // 页面显示时刷新数据
  onShow() {
    // 页面显示时重新加载当前tab的数据
    this.loadOrderListByStatus(this.getCurrentStatus());
    uni.getStorage({
      key: "selectAddress",
      success: (e) => {
        this.recinfo = e.data;
        this.addressId = e.data.id;
      },
    });
  },
  onPageScroll(e) {
    return;
    //兼容iOS端下拉时顶部漂移
    this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
  },

  // 下拉刷新
  onPullDownRefresh() {
    // 根据当前选中的tab状态刷新订单
    let status = null;
    switch (this.tabbarIndex) {
      case 0: // 全部
        status = null;
        break;
      case 1: // 待发货
        status = "PENDING_SHIP";
        break;
      case 2: // 待收货
        status = "SHIPPED";
        break;
      case 3: // 待付款
        status = "PENDING_PAYMENT";
        break;
      case 4: // 申请退货
        status = "RETURN_REQUESTED";
        break;
      case 5: // 退货同意
        status = "RETURN_APPROVED";
        break;
      case 6: // 退货拒绝
        status = "RETURN_REJECTED";
        break;
      case 7: // 已退货
        status = "RETURNED";
        break;
    }
    this.refreshOrderList(status);
  },
  methods: {
    // 检查网络连接
    checkNetwork() {
      return new Promise((resolve) => {
        uni.getNetworkType({
          success: (res) => {
            if (res.networkType === "none") {
              uni.showToast({
                title: "请检查网络连接",
                icon: "none",
              });
              resolve(false);
            } else {
              resolve(true);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      });
    },

    // 加载订单列表
    async loadOrderList(status = null) {
      // 检查网络连接
      const isConnected = await this.checkNetwork();
      if (!isConnected) {
        this.loadTestData();
        return;
      }

      try {
        uni.showLoading({
          title: "加载中...",
        });

        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          uni.navigateTo({ url: "/pages/login/pre-login" });
          return;
        }

        const params = {
          customerId,
          pageNum: 1,
          pageSize: 50,
        };

        // 如果指定了状态，添加status参数
        if (status) {
          params.status = status;
        }

        const response = await getOrderList(params);

        let ordersData = null;
        // 兼容两种响应结构：{ list, total, ... } 或 { data: { list, total, ... } }
        if (response && Array.isArray(response.list)) {
          ordersData = response.list;
        } else if (
          response &&
          response.data &&
          Array.isArray(response.data.list)
        ) {
          ordersData = response.data.list;
        }
        this.orderList = this.groupOrdersByStatus(ordersData);
        this.showType(this.tabbarIndex);
      } catch (error) {
        this.handleApiError(error, "加载订单列表");
      } finally {
        uni.hideLoading();
      }
    },

    // 刷新订单列表
    async refreshOrderList(status = null) {
      // 检查网络连接
      const isConnected = await this.checkNetwork();
      if (!isConnected) {
        uni.stopPullDownRefresh();
        return;
      }

      this.isRefreshing = true;
      try {
        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.stopPullDownRefresh();
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        const params = {
          customerId,
          pageNum: 1,
          pageSize: 50,
        };

        // 如果指定了状态，添加status参数
        if (status) {
          params.status = status;
        }

        const response = await getOrderList(params);

        // 使用相同的数据提取逻辑（兼容两种结构）
        let ordersData = null;
        if (response && Array.isArray(response.list)) {
          ordersData = response.list;
        } else if (
          response &&
          response.data &&
          Array.isArray(response.data.list)
        ) {
          ordersData = response.data.list;
        }

        if (Array.isArray(ordersData)) {
          // 如果是按状态查询，直接设置list数据
          if (status) {
            this.list = ordersData;
          } else {
            // 如果是查询全部，则进行分组
            this.orderList = this.groupOrdersByStatus(ordersData);
            this.list = this.orderList[this.tabbarIndex] || [];
          }

          uni.showToast({
            title: "刷新成功",
            icon: "success",
          });
        }
      } catch (error) {
        this.handleApiError(error, "刷新订单列表");
      } finally {
        this.isRefreshing = false;
        uni.stopPullDownRefresh();
      }
    },

    // 按状态分组订单
    groupOrdersByStatus(orders) {
      const grouped = {
        0: [], // 全部
        1: [], // 待发货
        2: [], // 待收货
        3: [], // 待付款
        4: [], // 申请退货
        5: [], // 退货同意
        6: [], // 退货拒绝
        7: [], // 已退货
      };

      // 检查orders是否为数组
      if (!orders || !Array.isArray(orders)) {
        return grouped;
      }
      orders.forEach((order) => {
        // 全部订单
        grouped[0].push(order);

        // 按状态分组（根据后端实际状态枚举）
        switch (order.status) {
          case "PENDING_SHIP": // 等待商家发货 - 待发货
            grouped[1].push(order);
            break;
          case "SHIPPED": // 商家已发货 - 待收货
            grouped[2].push(order);
            break;
          case "PENDING_PAYMENT": // 待付款
            grouped[3].push(order);
            break;
          case "RETURN_REQUESTED": // 退货申请中
            grouped[4].push(order);
            break;
          case "RETURN_APPROVED": // 退货已同意
            grouped[5].push(order);
            break;
          case "RETURN_REJECTED": // 退货被拒绝
            grouped[6].push(order);
            break;
          case "RETURNED": // 已退货
            grouped[7].push(order);
            break;
          case "COMPLETED": // 交易已完成
          case "CANCELLED": // 订单已取消
            // 仅保留在"全部"
            break;
          default:
            // 未知状态也放入全部订单
            break;
        }
      });

      return grouped;
    },

    // 获取状态文本
    getStatusText(status) {
      return this.statusText[status] || "未知状态";
    },

    // 计算总商品数量
    getTotalItems(orderItems) {
      if (!orderItems || !Array.isArray(orderItems)) return 0;
      return orderItems.reduce((total, item) => {
        return total + (parseInt(item.pNumber) || 0);
      }, 0);
    },

    // 格式化订单时间
    formatOrderTime(orderTime) {
      if (!orderTime) return "";
      const date = new Date(orderTime);
      const now = new Date();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));

      if (days === 0) {
        return (
          "今天 " +
          date.toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
          })
        );
      } else if (days === 1) {
        return (
          "昨天 " +
          date.toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
          })
        );
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return date.toLocaleDateString("zh-CN");
      }
    },

    showType(tbIndex) {
      this.tabbarIndex = tbIndex;

      // 根据tab索引确定要查询的状态
      let status = null;
      switch (tbIndex) {
        case 0: // 全部
          status = null;
          break;
        case 1: // 待发货
          status = "PENDING_SHIP";
          break;
        case 2: // 待收货
          status = "SHIPPED";
          break;
        case 3: // 待付款
          status = "PENDING_PAYMENT";
          break;
        case 4: // 申请退货
          status = "RETURN_REQUESTED";
          break;
        case 5: // 退货同意
          status = "RETURN_APPROVED";
          break;
        case 6: // 退货拒绝
          status = "RETURN_REJECTED";
          break;
        case 7: // 已退货
          status = "RETURNED";
          break;
      }

      // 重新加载对应状态的订单
      this.loadOrderListByStatus(status);
    },

    // 获取当前选中的状态
    getCurrentStatus() {
      switch (this.tabbarIndex) {
        case 0: // 全部
          return null;
        case 1: // 待发货
          return "PENDING_SHIP";
        case 2: // 待收货
          return "SHIPPED";
        case 3: // 待付款
          return "PENDING_PAYMENT";
        case 4: // 申请退货
          return "RETURN_REQUESTED";
        case 5: // 退货同意
          return "RETURN_APPROVED";
        case 6: // 退货拒绝
          return "RETURN_REJECTED";
        case 7: // 已退货
          return "RETURNED";
        default:
          return null;
      }
    },

    // 根据状态加载订单列表
    async loadOrderListByStatus(status) {
      // 检查网络连接
      const isConnected = await this.checkNetwork();
      if (!isConnected) {
        this.loadTestData();
        return;
      }

      try {
        uni.showLoading({
          title: "加载中...",
        });

        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        const params = {
          customerId,
          pageNum: 1,
          pageSize: 50,
        };

        // 如果指定了状态，添加status参数
        if (status) {
          params.status = status;
        }

        const response = await getOrderList(params);

        let ordersData = null;
        // 兼容两种响应结构
        if (response && Array.isArray(response.list)) {
          ordersData = response.list;
        } else if (
          response &&
          response.data &&
          Array.isArray(response.data.list)
        ) {
          ordersData = response.data.list;
        }

        // 直接设置当前tab的列表数据
        this.list = ordersData || [];
      } catch (error) {
        this.handleApiError(error, "加载订单列表");
        this.list = [];
      } finally {
        uni.hideLoading();
      }
    },

    cancelOrder(row) {
      uni.showModal({
        title: "取消订单",
        editable: true,
        placeholderText: "请输入取消原因（可选）",
        success: (res) => {
          if (res.confirm) {
            this.doCancelOrder(row.id, res.content || "");
          }
        },
      });
    },

    async doCancelOrder(orderId, reason = "") {
      if (this.isCancelling) return;
      this.isCancelling = true;
      try {
        uni.showLoading({ title: "取消订单中..." });
        await cancelOrder(orderId, reason);
        await this.refreshOrderList();
        uni.showToast({ title: "订单已取消", icon: "success" });
      } catch (error) {
        this.handleApiError(error, "取消订单");
      } finally {
        this.isCancelling = false;
        uni.hideLoading();
      }
    },

    toPayment(row) {
      //本地模拟订单提交UI效果
      uni.showLoading({
        title: "正在获取订单...",
      });
      let paymentOrder = [];
      paymentOrder.push(row);
      setTimeout(() => {
        uni.setStorage({
          key: "paymentOrder",
          data: paymentOrder,
          success: () => {
            uni.hideLoading();
            uni.navigateTo({
              url: "../../pay/payment/payment?amount=" + row.orderPrice,
            });
          },
        });
      }, 500);
    },

    async confirmReceive(row) {
      // 根据订单状态显示不同的确认消息
      let content = "确认已收到商品？";
      if (row.status === "RETURN_REJECTED") {
        content = "退货申请已被拒绝，确认收货后订单将完成。确认已收到商品？";
      }

      uni.showModal({
        title: "确认收货",
        content: content,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({
                title: "确认收货中...",
              });

              await confirmReceive(row.id);

              // 更新订单状态为待付款
              this.updateOrderStatus(row.id, "PENDING_PAYMENT");
              this.refreshOrderList();

              uni.showToast({
                title: "确认收货成功",
                icon: "success",
              });
            } catch (error) {
              this.handleApiError(error, "确认收货");
            } finally {
              uni.hideLoading();
            }
          }
        },
      });
    },

    returnGoods(row) {
      // 跳转到退货商品选择页面
      uni.navigateTo({
        url: `/pages/user/return_goods/return_goods?orderId=${row.id}`,
      });
    },

    async buyAgain(row) {
      try {
        uni.showLoading({ title: "处理中..." });

        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          uni.navigateTo({ url: "/pages/login/pre-login" });
          return;
        }

        if (
          !row ||
          !Array.isArray(row.orderItems) ||
          row.orderItems.length === 0
        ) {
          uni.showToast({ title: "该订单没有可购买的商品", icon: "none" });
          return;
        }

        const buylist = row.orderItems.map((item) => {
          const product = item.product || {};
          return {
            img: product.pImgUrl || "/static/img/noorder.png",
            name: product.pName || "",
            pSpecifications: product.pSpecifications || "",
            pPrice: item.pPrice || 0,
            number: parseInt(item.pNumber) || 1,
            productId: item.productId || product.id || "",
          };
        });

        // 写入确认页所需的本地数据
        await new Promise((resolve, reject) => {
          uni.setStorage({
            key: "buylist",
            data: buylist,
            success: resolve,
            fail: reject,
          });
        });

        uni.showToast({ title: "已加入确认订单", icon: "success" });

        // 跳转到确认订单页面（非tab页，用 navigateTo）
        setTimeout(() => {
          uni.navigateTo({ url: "/pages/order/confirmation?productFlag=true" });
        }, 500);
      } catch (error) {
        this.handleApiError(error, "再次购买");
      } finally {
        uni.hideLoading();
      }
    },

    viewRefundProgress(row) {
      uni.navigateTo({
        url: `/pages/user/order_detail/order_detail?id=${row.id}`,
      });
    },

    updateOrderStatus(orderId, newStatus) {
      const keys = Object.keys(this.orderList || {});
      for (const key of keys) {
        const group = this.orderList[key];
        if (Array.isArray(group) && group.length > 0) {
          for (let j = 0; j < group.length; j++) {
            if (group[j].id == orderId) {
              group[j].status = newStatus;
              this.showType(this.tabbarIndex);
              return;
            }
          }
        }
      }
    },
    // 待确认操作-同意|拒绝
    async conformOrderFun(row, status) {
      try {
        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          uni.navigateTo({ url: "../login/pre-login" });
          return;
        }
        // if (
        //   !row ||
        //   !Array.isArray(row.orderItems) ||
        //   row.orderItems.length === 0
        // ) {
        //   uni.showToast({ title: "该订单没有可购买的商品", icon: "none" });
        //   return;
        // }
        uni.showLoading({ title: "处理中..." });
        if (status == "CONFIRMED") {
          // 确认报价
          if (!this.addressId) {
            uni.showModal({
              title: "操作确认",
              content: "同意之前请先选择您的地址，以便供应商为您发货",
              success: function (res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/pages/user/address/address?type=select",
                  });
                } else if (res.cancel) {
                  return;
                }
              },
            });
          } else {
            const params = {
              customerId,
              status,
              id: row.productRequirementId,
              addressId: this.addressId,
            };
            const res = await conformOrder(params);
            if (res.data.ok) {
              uni.showToast({ title: res.data.message, icon: "success" });
              this.refreshOrderList();
            } else {
              uni.showToast({ title: res.data.message, icon: "none" });
            }
          }
        } else {
          // 拒绝报价
          const params = {
            customerId,
            status,
            id: row.productRequirementId,
            addressId: "",
          };
          const res = await conformOrder(params);
          if (res.data.ok) {
            uni.showToast({ title: res.data.message, icon: "success" });
            this.refreshOrderList();
          } else {
            uni.showToast({ title: res.data.message, icon: "none" });
          }
        }
      } catch (error) {
        this.handleApiError(error, "再次购买");
      } finally {
        uni.hideLoading();
      }
    },
    // 跳转到订单详情
    goOrderDetail(row) {
      if (!row || !row.id) {
        uni.showToast({
          title: "订单数据无效",
          icon: "none",
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/user/order_detail/order_detail?id=${row.id}`,
      });
    },

    // 获取商品名称
    getProductName(row) {
      return row.product.pName;
    },

    // 获取商品图片
    getProductImage(item) {
      return getFirstImage(item.product.pImgUrl);
    },

    // 处理API错误
    handleApiError(error, operation) {
      uni.showToast({
        title: `${operation}失败`,
        icon: "none",
      });
    },

    // 获取订单价格标签
    getOrderPriceLabel(status) {
      switch (status) {
        case "RETURN_REQUESTED":
          return "订单金额";
        case "RETURN_APPROVED":
        case "RETURNED":
          return "剩余金额";
        case "RETURN_REJECTED":
          return "订单金额";
        default:
          return "合计";
      }
    },

    // 获取显示的订单金额
    getDisplayOrderPrice(order) {
      if (!order) return "0.00";

      const originalTotal = parseFloat(order.orderPrice) || 0;

      // 根据订单状态计算显示金额
      if (order.status === "RETURN_APPROVED" || order.status === "RETURNED") {
        // 退货同意/已退货状态：显示总金额 - 退货商品金额
        const returnAmount = this.calculateOrderReturnAmount(order);
        const remainingTotal = originalTotal - returnAmount;
        return Math.max(0, remainingTotal).toFixed(2);
      }

      // 其他状态显示原订单金额
      return originalTotal.toFixed(2);
    },

    // 计算订单的退货金额
    calculateOrderReturnAmount(order) {
      if (!order || !order.orderItems) return 0;

      try {
        // 尝试解析 remark 字段中的退货商品信息
        if (order.remark) {
          const returnItems = JSON.parse(order.remark);

          // 如果成功解析出退货商品信息，说明是部分退货
          if (Array.isArray(returnItems) && returnItems.length > 0) {
            return order.orderItems
              .filter((orderItem) => {
                return returnItems.some(
                  (returnItem) => returnItem.orderItemId === orderItem.id
                );
              })
              .reduce((sum, orderItem) => {
                const returnItem = returnItems.find(
                  (ri) => ri.orderItemId === orderItem.id
                );
                const quantity = returnItem
                  ? returnItem.returnQuantity
                  : parseInt(orderItem.pNumber);
                const price = parseFloat(orderItem.pPrice) || 0;
                return sum + quantity * price;
              }, 0);
          }
        }

        // 如果没有具体的退货商品信息，说明是整单退货
        return order.orderItems.reduce((sum, item) => {
          const quantity = parseInt(item.pNumber) || 0;
          const price = parseFloat(item.pPrice) || 0;
          return sum + quantity * price;
        }, 0);
      } catch (error) {
        console.warn("计算订单退货金额失败:", error);
        // 解析失败时，按整单退货计算
        return order.orderItems.reduce((sum, item) => {
          const quantity = parseInt(item.pNumber) || 0;
          const price = parseFloat(item.pPrice) || 0;
          return sum + quantity * price;
        }, 0);
      }
    },

    // 计算剩余金额（总金额 - 退货金额）
    getRemainingAmount(order) {
      if (!order) return 0;

      const originalTotal = parseFloat(order.orderPrice) || 0;
      const returnAmount = this.calculateOrderReturnAmount(order);
      const remainingAmount = originalTotal - returnAmount;

      return Math.max(0, remainingAmount);
    },

    // 添加发票抬头
    addInvoiceInfo(order) {
      if (!order || !order.id) {
        uni.showToast({
          title: "订单信息无效",
          icon: "none",
        });
        return;
      }

      // 跳转到发票抬头填写页面
      uni.navigateTo({
        url: `/pages/user/invoice/invoice?orderId=${order.id}`,
        success: () => {},
        fail: (err) => {
          uni.showToast({
            title: "页面跳转失败",
            icon: "none",
          });
        },
      });
    },

    // 查看发票
    async viewInvoice(order) {
      try {
        uni.showLoading({
          title: "加载中...",
        });

        const res = await getInvoiceInfo(order.id);

        // 处理多层响应结构
        let invoiceImageUrl = null;
        if (res?.data?.data?.invoiceImageUrl) {
          invoiceImageUrl = res.data.data.invoiceImageUrl;
        } else if (res?.data?.invoiceImageUrl) {
          invoiceImageUrl = res.data.invoiceImageUrl;
        } else if (res?.invoiceImageUrl) {
          invoiceImageUrl = res.invoiceImageUrl;
        }

        uni.hideLoading(); // 先隐藏loading

        if (invoiceImageUrl) {
          // 有发票图片，跳转到发票查看页面
          uni.navigateTo({
            url: `/pages/user/invoice_view/invoice_view?orderId=${
              order.id
            }&imageUrl=${encodeURIComponent(invoiceImageUrl)}`,
          });
        } else {
          // 没有发票图片
          uni.showToast({
            title: "暂无发票图片",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading(); // 确保隐藏loading
        this.handleApiError(error, "获取发票信息");
      }
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f3f3f3;
}

.topTabBar {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 10;
  background-color: #f8f8f8;
  height: 80upx;
  display: flex;
  justify-content: space-around;

  .grid {
    width: 12%;
    height: 80upx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #444;
    font-size: 24upx;

    .text {
      height: 76upx;
      display: flex;
      align-items: center;

      &.on {
        color: #f06c7a;
        border-bottom: solid 4upx #f06c7a;
      }
    }
  }
}

.order-list {
  margin-top: 80upx;
  padding-top: 20upx;
  padding-bottom: 40upx;
  width: 100%;

  .debug-btn {
    width: 94%;
    margin: 0 auto 20upx;
    height: 80upx;
    background-color: #007aff;
    border-radius: 10upx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 28upx;
  }

  .refresh-tip {
    width: 100%;
    height: 60upx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f8f8f8;
    font-size: 24upx;
    color: #666;
  }

  .order-info {
    display: flex;
    padding: 10px;
    border-bottom: 1px solid #f1f1f1;
    /* 添加底部边框 */
  }

  .order-info:last-child {
    border-bottom: none;
    /* 去掉最后一个商品项的边框 */
  }

  .list {
    width: 94%;
    margin: 0 auto;

    .onorder {
      width: 100%;
      height: 50vw;
      display: flex;
      justify-content: center;
      align-content: center;
      flex-wrap: wrap;

      image {
        width: 20vw;
        height: 20vw;
        border-radius: 100%;
      }

      .text {
        width: 100%;
        height: 60upx;
        font-size: 28upx;
        color: #444;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .row {
      width: calc(100% - 40upx);
      padding: 10upx 20upx;
      border-radius: 10upx;
      background-color: #fff;
      margin-bottom: 20upx;

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50upx;
        margin-bottom: 10upx;

        .type {
          font-size: 26upx;
          color: #ec652f;
        }

        .order-time {
          font-size: 22upx;
          color: #999;
        }
      }

      .order-info {
        width: 100%;
        display: flex;

        .left {
          flex-shrink: 0;
          width: 25vw;
          height: 25vw;

          image {
            width: 25vw;
            height: 25vw;
            border-radius: 10upx;
          }
        }

        .right {
          width: 100%;
          margin-left: 10upx;
          position: relative;

          .name {
            width: 100%;
            font-size: 28upx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }

          .spec {
            color: #a7a7a7;
            font-size: 22upx;
          }

          .price-number {
            position: absolute;
            bottom: 0;
            width: 100%;
            display: flex;
            justify-content: flex-end;
            font-size: 22upx;
            color: #333;
            display: flex;
            align-items: flex-end;
            right: 20upx;
          }
        }
      }

      .detail {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        height: 60upx;
        font-size: 26upx;

        .sum {
          padding: 0 8upx;
          display: flex;
          align-items: flex-end;

          .price {
            font-size: 30upx;
          }
        }
      }

      .btns {
        height: 80upx;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        view {
          min-width: 120upx;
          height: 50upx;
          padding: 0 20upx;
          border-radius: 50upx;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 28upx;
          margin-left: 20upx;
        }

        .default {
          border: solid 1upx #ccc;
          color: #666;
        }

        .pay {
          border: solid 1upx #ec652f;
          color: #ec652f;
        }
      }
    }
  }
}
</style>
